<!doctype html>
{% include 'header.html' %}

{% include 'search.html' %}

{% macro genlink(func, filename) -%}
    <a href="/{{func}}/{{ filename }}/{{ session['grepnumlines'] }}">{{func}}</a>
{%- endmacro %}

{% for filename in session['validfiles']|sort %}
        <div class="logfile">
                {{ session['validfiles'].get(filename)[0] }} -
                {{ genlink('head', filename) }} &nbsp;<span style="color:#cecece">&#124;</span> &nbsp;
                {{ genlink('tail', filename) }}
                - {{ session['validfiles'].get(filename)[1] }} bytes
            <a href="#" onclick="startStream('{{ filename }}')">Real-time Stream</a>

        </div>
{% endfor %}

<div id="stream-container" style="display:none; margin-top: 20px;">
    <h3>Real-time Log Stream</h3>
    <button onclick="stopStream()">Stop Streaming</button>
    <div id="log-stream" style="height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; font-family: monospace; background: #f8f8f8;"></div>
</div>

<script>
let eventSource = null;

function startStream(filename) {
    // 显示流容器
    document.getElementById('stream-container').style.display = 'block';
    const logDiv = document.getElementById('log-stream');
    logDiv.innerHTML = 'Starting real-time stream...</br>';

    // 停止现有的连接（如果有）
    if (eventSource) {
        eventSource.close();
    }

    // 创建新的EventSource连接
    eventSource = new EventSource(`/stream/${filename}/`);

    eventSource.onmessage = function(event) {
        // 添加新日志行
        logDiv.innerHTML += event.data + '</br>';

        // 自动滚动到底部
        logDiv.scrollTop = logDiv.scrollHeight;
    };

    eventSource.onerror = function(error) {
        console.error('EventSource error:', error);
        logDiv.innerHTML += 'Connection error or closed.\n';
        eventSource.close();
    };
}

function stopStream() {
    if (eventSource) {
        eventSource.close();
        eventSource = null;
    }
    document.getElementById('stream-container').style.display = 'none';
    document.getElementById('log-stream').innerHTML = '';
}
</script>
{% include 'footer.html' %}
